package com.athuiju.fenxiaoback.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.athuiju.fenxiaoback.entity.*;
import com.athuiju.fenxiaoback.entity.vo.*;
import com.athuiju.fenxiaoback.enume.OrderStatusEnum;
import com.athuiju.fenxiaoback.interceptor.LoginUserInterceptor;
import com.athuiju.fenxiaoback.mapper.TbOrderMapper;
import com.athuiju.fenxiaoback.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author athuiju
 * @since 2021-06-30
 */
@Service
public class TbOrderServiceImpl extends ServiceImpl<TbOrderMapper, TbOrder> implements TbOrderService {

    @Autowired
    private  UmsMemberReceiveAddressService memberReceiveAddressService;

    @Autowired
    private TbCartService cartService;

    @Autowired
    private WmsWareSkuService wareSkuService;

    @Autowired
    UcenterMemberService memberService;

    @Autowired
    WmsWareInfoService wareInfoService;

    @Autowired
    TbCartitemService  cartitemService;


    @Autowired
    TbSpuService spuService;

    @Autowired
    OmsOrderService omsOrderService;

    @Autowired
    OmsOrderItemService omsOrderItemService;

    @Transactional
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo,String memberid) throws Exception{
        SubmitOrderResponseVo submitVo = new SubmitOrderResponseVo();
        // 0：正常
        submitVo.setCode(0);
        // 1 .创建订单等信息
        //submitOrder1.1
        OrderCreateTo order = createOrder(vo,memberid);

        //2.验价
        BigDecimal payAmount = order.getOrder().getPayAmount();
        BigDecimal voPayPrice = vo.getPayPrice();
        if(!(Math.abs(payAmount.subtract(voPayPrice).doubleValue()) < 0.01)){

            submitVo.setCode(-1);

        }
        // 金额对比成功
        // 3.保存订单
        saveOrder(order);

        //4.移除购物车中的购物项
        List<OmsOrderItem> orderItems = order.getOrderItems();
        for(int i=0;i<orderItems.size();i++){
            Long skuId = orderItems.get(i).getSkuId();
            cartitemService.remove(new QueryWrapper<TbCartitem>().eq("skuId",skuId));
        }


        submitVo.setOrderEntity(order.getOrder());



        return submitVo;
    }


    /**
     * 保存订单所有数据
     */
    private void saveOrder(OrderCreateTo order) {
        OmsOrder orderEntity = order.getOrder();
        orderEntity.setModifyTime(new Date());
        omsOrderService.save(orderEntity);


        List<OmsOrderItem> orderItems = order.getOrderItems();
        orderItems = orderItems.stream().map(item -> {
            item.setOrderId(orderEntity.getId());
            item.setSpuName(item.getSpuName());
            item.setOrderSn(order.getOrder().getOrderSn());
            return item;
        }).collect(Collectors.toList());
        omsOrderItemService.saveBatch(orderItems);
    }

    public static String getOrderIdByTime() {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
        String newDate=sdf.format(new Date());
        String result="";
        Random random=new Random();
        for(int i=0;i<3;i++){
            result+=random.nextInt(10);
        }
        return newDate+result;
    }

    // //submitOrder1.2
    private OrderCreateTo createOrder(OrderSubmitVo vo,String memberid) throws Exception {
        OrderCreateTo orderCreateTo = new OrderCreateTo();


        String replaceUUID = UUID.randomUUID().toString().replace("-", "");
        String currentTimeMillis = String.valueOf(System.currentTimeMillis());
        //return
        // 1. 生成一个订单号
        //String orderSn = IdWorker.getTimeId();
        //String orderSn =replaceUUID + currentTimeMillis;
        String orderSn =getOrderIdByTime();
        //submitOrder1.3  构建订单
        OmsOrder orderEntity = buildOrderSn(vo,orderSn,memberid);

        // 2. 获取所有被选中的订单项  //submitOrder1.3  构建订单项
        List<OmsOrderItem> items = buildOrderItems(orderSn,memberid);

        // 3.验价	传入订单 、订单项 计算价格、积分、成长值等相关信息
        computerPrice(orderEntity,items);
        orderCreateTo.setOrder(orderEntity);
        orderCreateTo.setOrderItems(items);
        return orderCreateTo;
    }

    private void computerPrice(OmsOrder orderEntity, List<OmsOrderItem> items) {
        BigDecimal totalPrice = new BigDecimal("0.0");
        // 叠加每一个订单项的金额
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal integration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");
        BigDecimal gift = new BigDecimal("0.0");
        BigDecimal growth = new BigDecimal("0.0");
        for (OmsOrderItem item : items) {
            // 优惠券的金额
            coupon = coupon.add(item.getCouponAmount());
            // 积分优惠的金额
            integration = integration.add(item.getIntegrationAmount());
            // 打折的金额
            promotion = promotion.add(item.getPromotionAmount());
            BigDecimal realAmount = item.getRealAmount();
            totalPrice = totalPrice.add(realAmount);

            // 购物获取的积分、成长值
            gift.add(new BigDecimal(item.getGiftIntegration().toString()));
            growth.add(new BigDecimal(item.getGiftGrowth().toString()));
        }
        // 1.订单价格相关 总额、应付总额
        orderEntity.setTotalAmount(totalPrice);
        orderEntity.setPayAmount(totalPrice.add(orderEntity.getFreightAmount()));

        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegrationAmount(integration);
        orderEntity.setCouponAmount(coupon);

        // 设置积分、成长值
        orderEntity.setIntegration(gift.intValue());
        orderEntity.setGrowth(growth.intValue());

        // 设置订单的删除状态
        orderEntity.setDeleteStatus(OrderStatusEnum.CREATE_NEW.getCode());
    }


    /**
     * 为 orderSn 订单构建订单数据
     */
    private List<OmsOrderItem> buildOrderItems(String orderSn,String memberid) {
        // TODO 这里是最后一次来确认购物项的价格 这个远程方法还会查询一次数据库
        //
        List<TbCartitem> cartItems = cartitemService.getUserCheckedCartItems(memberid);
        List<OmsOrderItem> itemEntities = null;
        if(cartItems != null && cartItems.size() > 0){
            itemEntities = cartItems.stream().map(cartItem -> {
                OmsOrderItem itemEntity = buildOrderItem(cartItem);
                itemEntity.setOrderSn(orderSn);
                return itemEntity;
            }).collect(Collectors.toList());
        }
        return itemEntities;
    }

    /**
     * 构建某一个订单项
     */
    //
    private OmsOrderItem buildOrderItem(TbCartitem cartItem) {
        OmsOrderItem itemEntity = new OmsOrderItem();
        // 1.订单信息： 订单号

        // 2.商品spu信息
        Long skuId =Long.parseLong(cartItem.getSkuId());
        SpuInfoVo spuInfo = spuService.getSkuInfoBySkuId(skuId);
        itemEntity.setSpuId(spuInfo.getId());
        itemEntity.setSpuBrand(spuInfo.getBrandId().toString());
        itemEntity.setSpuName(spuInfo.getSpuName());
        itemEntity.setCategoryId(spuInfo.getCatalogId());
        // 3.商品的sku信息
        itemEntity.setSkuId(Long.parseLong(cartItem.getSkuId()));
        itemEntity.setSkuName(cartItem.getTitle());
        itemEntity.setSkuPic(cartItem.getImage());
        itemEntity.setSkuPrice(cartItem.getPrice());
        // 把一个集合按照指定的字符串进行分割得到一个字符串
        String skuAttr = StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";");
        itemEntity.setSkuAttrsVals(skuAttr);
        itemEntity.setSkuQuantity(cartItem.getCount());
        // 4.积分信息 买的数量越多积分越多 成长值越多
        itemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount())).intValue());
        itemEntity.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount())).intValue());
        // 5.订单项的价格信息 优惠金额
        itemEntity.setPromotionAmount(new BigDecimal("0.0"));
        itemEntity.setCouponAmount(new BigDecimal("0.0"));
        itemEntity.setIntegrationAmount(new BigDecimal("0.0"));
        // 当前订单项的实际金额
        BigDecimal orign = itemEntity.getSkuPrice().multiply(new BigDecimal(itemEntity.getSkuQuantity().toString()));
        // 减去各种优惠的价格
        BigDecimal subtract = orign.subtract(itemEntity.getCouponAmount()).subtract(itemEntity.getPromotionAmount()).subtract(itemEntity.getIntegrationAmount());
        itemEntity.setRealAmount(subtract);
        //return null;
        return itemEntity;
    }



    /**
     * 构建一个订单
     */
    private OmsOrder buildOrderSn(OrderSubmitVo vo,String orderSn,String memberid) throws Exception {
        OmsOrder entity = new OmsOrder();
        entity.setOrderSn(orderSn);
        entity.setCreateTime(new Date());
        entity.setCommentTime(new Date());
        entity.setReceiveTime(new Date());
        entity.setDeliveryTime(new Date());
        //   查询会员信息
        UcenterMember rsepVo = memberService.getById(memberid);
        entity.setMemberId(rsepVo.getId());
        entity.setMemberUsername(rsepVo.getNickname());
        entity.setBillReceiverEmail(rsepVo.getEmail());


        // 2. 获取收获地址信息

        //R fare = wmsFeignService.getFare(vo.getAddrId());
        // 根据地址id获取运费
        FareVo resp = wareInfoService.getFare(vo.getAddrId(),memberid);
        if (resp.getCode()==-1){
            throw  new Exception("此用户没有这个地址");
        }


        //FareVo resp = fare.getData(new TypeReference<FareVo>() {});
        entity.setFreightAmount(resp.getFare());
        if (StringUtils.isEmpty(resp.getMemberReceiveAddress().getCity() )){
            throw new Exception("地址没有选择城市，给地址添加城市");
        }
        entity.setReceiverCity(resp.getMemberReceiveAddress().getCity());
        entity.setReceiverDetailAddress(resp.getMemberReceiveAddress().getDetailAddress());


        entity.setDeleteStatus(OrderStatusEnum.CREATE_NEW.getCode());
        entity.setReceiverPhone(resp.getMemberReceiveAddress().getPhone());
        entity.setReceiverName(resp.getMemberReceiveAddress().getName());
        entity.setReceiverPostCode(resp.getMemberReceiveAddress().getPostCode());
        entity.setReceiverProvince(resp.getMemberReceiveAddress().getProvince());
        entity.setReceiverRegion(resp.getMemberReceiveAddress().getRegion());
        // 设置订单状态
        entity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        entity.setAutoConfirmDay(7);
        return entity;
    }





    @Override
    public OrderConfirmVo confirmOrder(String memberid) {
        //确认订单页面数据
        OrderConfirmVo confirmVo = new OrderConfirmVo();

        //1.查询用户地址列表
        List<UmsMemberReceiveAddress> addresses= memberReceiveAddressService.getAddress(memberid);
        confirmVo.setAddress(addresses);


        //2.查询购物车服务
        List<TbCartitem> items = cartService.getCurrentUserCartItems(memberid);
        confirmVo.setItems(items);

        //3.查询购物项是否还有库存
        List<String> skuIds = items.stream().map(item -> item.getSkuId()).collect(Collectors.toList());
        List<SkuStockVo>  data=  wareSkuService.getSkuHasStock(skuIds);
        // 各个商品id 与 他们库存状态的映射
        Map<Long, Boolean> stocks = data.stream().collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::getHasStock));
        confirmVo.setStocks(stocks);


        // 4.查询用户积分
        UcenterMember member = memberService.getById(memberid);
        confirmVo.setIntegration(member.getIntegration());


        return confirmVo;
    }


}
